package com.zsr.example.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zsr.example.dto.session.WebsocketMessageDTO;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

import static com.zsr.example.util.constants.ChatTypeEnum.getChatType;

/**
 * @author zhousiren
 * @date 2022/2/16 23:04
 */
@ServerEndpoint("/webSocket/{username}")
@Component
public class WebSocketServiceImpl {
    private static int onlineCount = 0;
    private static Map<String, WebSocketServiceImpl> clients = new ConcurrentHashMap<String, WebSocketServiceImpl>();
    private Session session;
    private String username;

    public WebSocketServiceImpl() {
        //System.out.println("webSocket初始化...");
    }

    /**
     * 建立连接的时候
     **/
    @OnOpen
    public void onOpen(@PathParam("username") String username, Session session) throws IOException {

        this.username = username;
        this.session = session;

        addOnlineCount();
        clients.put(username, this);//username 为id
        //System.out.println("已连接");
    }

    @OnClose
    public void onClose() throws IOException {
        clients.remove(username);
        subOnlineCount();
    }

    @OnMessage
    public void onMessage(String message, Session session) throws IOException {
        //JSONObject jsonObject = JSONObject.parseObject(message);
        WebsocketMessageDTO messageDTO = JSON.parseObject(message, WebsocketMessageDTO.class);
        switch (Objects.requireNonNull(getChatType(messageDTO.getType()))) {
            case HEART_BEAT:
                // 心跳消息
                messageDTO.setData("pong");
                session.getBasicRemote().sendText(JSON.toJSONString(messageDTO));
            case SEND_MESSAGE:
                // 发送消息
                // ChatRecord chatRecord = JSON.parseObject(JSON.toJSONString(messageDTO.getData()), ChatRecord.class);
                // 过滤html标签
                //chatRecord.setContent(HTMLUtils.deleteTag(chatRecord.getContent()));
                //chatRecordDao.insert(chatRecord);
                if(!StringUtils.isEmpty(messageDTO.getTo())){
                    sendMessageTo(JSONObject.toJSONString(messageDTO.getData()), messageDTO.getTo());
                }
                // 广播消息
                //sendMessageAll(JSONObject.toJSONString(messageDTO.getData()));
                break;
            default:
                break;
        }

    }

    @OnError
    public void onError(Session session, Throwable error) {
        error.printStackTrace();
    }

    //给某个人发送信息
    public void sendMessageTo(String message, String To) throws IOException {
        for (WebSocketServiceImpl item : clients.values()) {
            if (item.username.equals(To) )
                item.session.getAsyncRemote().sendText(message);
        }
    }
    //给所有人发送信息
    public void sendMessageAll(String message) throws IOException {
        for (WebSocketServiceImpl item : clients.values()) {
            item.session.getAsyncRemote().sendText(message);
        }
    }

    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        WebSocketServiceImpl.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        WebSocketServiceImpl.onlineCount--;
    }
    public static synchronized Map<String, WebSocketServiceImpl> getClients() {
        return clients;
    }

    public Session getSession() {
        return session;
    }
}
